#include "threadpool.h"
#include "mysql.h" 
//********************************************************************************
//初始化线程池
//********************************************************************************
void threadpoolInit(thread_pool_t* pthreadpool, int threadNum)
{
	pthreadpool->threadNumber = threadNum;
	pthreadpool->threads = (pthread_t*)calloc(threadNum, sizeof(pthread_t));
	queueInit(&pthreadpool->queue);
}

//********************************************************************************
//销毁线程池
//********************************************************************************
void threadpoolDestroy(thread_pool_t* pthreadpool)
{
	free(pthreadpool->threads);
	queueDestroy(&pthreadpool->queue);
}

//********************************************************************************
//创建子线程，开启线程池
//********************************************************************************
void threadpoolStart(thread_pool_t * pthreadpool)
{
	for(int idx = 0; idx < pthreadpool->threadNumber; ++idx) {
		int ret = pthread_create(&pthreadpool->threads[idx],
			NULL, 
			threadFunc, 
			pthreadpool);
		THREAD_ERROR_CHECK(ret, "pthread_create");
	}
}

//********************************************************************************
//线程处理函数
//********************************************************************************
void * threadFunc(void* arg)
{
	//每一个子线程要做的事儿
	printf("sub thread %ld is runing\n", pthread_self());
	thread_pool_t * pthreadpool = (thread_pool_t*)arg;
// 	while(1)
// 	{
// 		task_t * pNode = taskDequeue(&pthreadpool->queue);
// 		printf("开始发送\n");
// 		Sendls(pNode->peerfd,pNode->data);
// 		printf("peerfd = %d,data = %s\n",pNode->peerfd,pNode->data);

// // //***********************可以在这里测试********************
// // //pNode->type表示指令类型,pNode->data表示参数。
// // //返回小火车结构体
// // 		train_t sendmsgs;
// // 		sendmsgs.len = 100;
// // 		strcpy(sendmsgs.data,pNode->data);
// // 		send(pNode->peerfd,&sendmsgs,sendmsgs.len + 4,MSG_WAITALL);
// // //********************************************************
		
// 		printf("发送完毕\n");
// 		free(pNode);
// 	}
	while(1) {
		task_t * pNode = taskDequeue(&pthreadpool->queue);
		//定义函数指针变量
		handleCmd handle;
		if(pNode != NULL) {
			//执行任务
			switch(pNode->type)
			{
				case CMD_TYPE_CD:
					cd(pNode->peerfd,pNode->data);
					break;
				case CMD_TYPE_LS:
					ls(pNode->peerfd,pNode->data);
					break;
				case CMD_TYPE_PWD:
					handle(pNode->peerfd,pNode->data);
					break;
				case CMD_TYPE_PUT:
					GetFile(pNode->peerfd,pNode->data);
					break;
				case CMD_TYPE_GET:
					PushFile(pNode->peerfd,pNode->data);
					break;
				case CMD_TYPE_RM:
					rmfile(pNode->peerfd,pNode->data);
					break;
				case CMD_TYPE_MKDIR:
					mkDir(pNode->peerfd,pNode->data);
					break;
				default:
					break;
			}
		} else {
			break;
		}
		//执行完毕释放结点
		free(pNode);
	}
	printf("sub thread %ld is ready to exit\n", pthread_self());
	pthread_exit(0);
}

